import { useState, useEffect } from 'react';
import { useAuth } from '@/hooks/use-auth';

export interface ParameterField {
  id: number;
  field_name: string;
  field_description: string;
  data_type: string;
  measurement_unit: string;
  measurement_class: string;
  data_source: string;
  example_description: string;
  is_required: boolean;
  parameter_value?: string;
}

export interface FilteredParameterField extends ParameterField {
  canEdit: boolean;
  isVisible: boolean;
}

export function useParameterPermissions(tableName: string, deviceId?: number) {
  const [fields, setFields] = useState<FilteredParameterField[]>([]);
  const [allFields, setAllFields] = useState<FilteredParameterField[]>([]); // 存储所有字段
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [editData, setEditData] = useState<Record<number, string>>({});
  
  // 获取用户权限信息
  const { user, permissions, canEditField, hasDataSourceAccess } = useAuth(tableName);
  

  useEffect(() => {
    if (tableName && user && permissions) {
      loadParameterFields();
    }
  }, [tableName, deviceId, user, permissions]);

  const loadParameterFields = async () => {
    try {
      setLoading(true);
      setError(null);

      // 获取字段元数据
      const metadataResponse = await fetch(`/api/field-metadata?tableName=${tableName}`);
      const metadataData = await metadataResponse.json();

      if (!metadataData.success) {
        throw new Error(metadataData.error || '获取字段元数据失败');
      }

      // 获取设备参数数据（如果有deviceId）
      let parameterData: any = {};
      if (deviceId) {
        const parameterResponse = await fetch(`/api/device-parameters?deviceId=${deviceId}&type=${tableName}`);
        const parameterResult = await parameterResponse.json();
        if (parameterResult.success && parameterResult.data) {
          parameterData = parameterResult.data;
        }
      }

      // 处理字段权限和可见性
      const fieldsArray = metadataData.data.fields || [];
      const processedFields: FilteredParameterField[] = fieldsArray.map((field: ParameterField) => {
        // 所有字段都可见 - 查询权限完全开放
        const isVisible = true;

        // 编辑权限基于用户角色和字段的数据来源
        const canEdit = (() => {
          // 如果没有用户信息，默认不可编辑
          if (!user || !permissions) {
            return false;
          }

          // 管理员可以编辑所有字段
          if (permissions.canEditAll) {
            return true;
          }

          // 查看角色不能编辑任何字段
          if (user.role_code === 'V') {
            return false;
          }

          // 其他角色只能编辑对应数据来源的字段
          const hasAccess = permissions.dataSourceAccess && permissions.dataSourceAccess.includes(field.data_source);
          return hasAccess;
        })();

        const normalizedFieldName = Array.isArray(field.field_name) ? field.field_name[0] : field.field_name;

        return {
          ...field,
          field_name: normalizedFieldName,
          parameter_value: parameterData[field.field_name] || '',
          canEdit,
          isVisible
        };
      });

      // 显示所有可见字段，权限控制在编辑层面
      const filteredFields = processedFields.filter(field => field.isVisible);

      // 按照权限排序：可编辑字段排在前面，然后按字段顺序排序
      const sortedFields = filteredFields.sort((a, b) => {
        // 首先按照是否可编辑排序（可编辑的在前）
        if (a.canEdit !== b.canEdit) {
          return a.canEdit ? -1 : 1;
        }
        // 然后按照原始字段顺序排序
        return a.field_sequence - b.field_sequence;
      });

      // 保存所有字段和过滤后的字段
      setAllFields(processedFields);
      setFields(sortedFields);

      // 初始化编辑数据
      const initialEditData: Record<number, string> = {};
      processedFields.forEach(field => {
        if (field.parameter_value) {
          initialEditData[field.id] = field.parameter_value;
        }
      });
      setEditData(initialEditData);

    } catch (error) {
      console.error('加载参数字段失败:', error);
      setError(error instanceof Error ? error.message : '加载参数字段失败');
    } finally {
      setLoading(false);
    }
  };

  const updateFieldValue = (fieldId: number, value: string) => {
    setEditData(prev => ({
      ...prev,
      [fieldId]: value
    }));
  };

  const saveParameters = async () => {
    if (!deviceId) {
      throw new Error('设备ID不能为空');
    }

    try {
      // 只保存用户有权限编辑的字段
      const editableFields = fields.filter(field => field.canEdit);
      const dataToSave: Record<string, string> = {};
      
      editableFields.forEach(field => {
        const value = editData[field.id];
        if (value !== undefined) {
          dataToSave[field.field_name] = value;
        }
      });

      const response = await fetch('/api/device-parameters', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId,
          type: tableName,
          data: dataToSave
        }),
      });

      const result = await response.json();
      
      if (!result.success) {
        throw new Error(result.error || '保存参数失败');
      }

      return result;
    } catch (error) {
      console.error('保存参数失败:', error);
      throw error;
    }
  };

  const getFieldsByDataSource = (dataSource: string) => {
    const result = allFields.filter(field => field.data_source === dataSource);
    console.log(`getFieldsByDataSource(${dataSource}): 从 ${allFields.length} 个字段中找到 ${result.length} 个字段`)
    return result;
  };

  const getEditableFieldsCount = () => {
    return fields.filter(field => field.canEdit).length;
  };

  const getVisibleFieldsCount = () => {
    return fields.filter(field => field.isVisible).length;
  };

  const getUserDataSources = () => {
    const sources = new Set(fields.map(field => field.data_source));
    return Array.from(sources).filter(source => hasDataSourceAccess(source));
  };

  return {
    fields,
    loading,
    error,
    editData,
    user,
    permissions,
    updateFieldValue,
    saveParameters,
    loadParameterFields,
    getFieldsByDataSource,
    getEditableFieldsCount,
    getVisibleFieldsCount,
    getUserDataSources,
    canEditField,
    hasDataSourceAccess
  };
}
